package com.asj.vivo.lock.service.oppoSdk.operation;

import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import static com.asj.enums.AppIdentifierDictEnums.app_packageName;
import static com.asj.enums.AppIdentifierDictEnums.supervision_initiate;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.DISABLE_APP_IN_LAUNCHER_FLAG;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.DISABLE_APP_IN_RECENT_TASK_FLAG;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.ENABLE_APP_IN_LAUNCHER_FLAG;
import static com.oplus.enterprise.mdmcoreservice.manager.DeviceRestrictionManager.ENABLE_APP_IN_RECENT_TASK_FLAG;

import android.content.Context;
import android.util.Log;

import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.service.oppoSdk.operation.base.OperationPair;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 针对软件层面的限制监管
 * */
public class SuperviseSoftwareOperation {

    public OPPOSDKService oppoSdkService;
    public Context context;

    public SuperviseSoftwareOperation(Context contexts) {
        this.context = contexts;
    }

    /**
     * 针对软件层面的限制监管
     * */
    public void superviseSoftware(String opType){
        oppoSdkService = new OPPOSDKService(context);

        List<OperationPair> executedOperations = new ArrayList<>();
        List<String> operationsToExecute = supervision_initiate.getValue().equals(opType) ? forwardOperations : reverseOperations;

        try {
            for (String operationName : operationsToExecute) {
                OperationPair operationPair = operationMap.get(operationName);
                if (operationPair != null) {
                    operationPair.execute();
                    executedOperations.add(operationPair);
                }
            }
        } catch (Exception e) {
            // 执行补偿
            rollback(executedOperations);
            Log.e(TAG, "软件层面的限制监管异常", e);
            throw new RuntimeException("软件层面的限制监管异常: " + e.getMessage());
        }
    }

    private final String packName = app_packageName.getValue();

    // 正向操作列表
    public final List<String> forwardOperations = List.of(
            "setEmmAdminTrue", "setDeviceOwner", "setSuperWhiteList",
            "addPersistentApp", "addDisallowedUninstallPackages",
            "addAppAlarmWhiteList", "setSystemUpdatePolicies0",
            "settingBatteryOptimizationsTrue", "disableAppInLauncher",
            "disableAppInRecentTask"
    );

    // 定义操作映射，将操作名称映射到操作对
    public final Map<String, OperationPair> operationMap = new HashMap<>();

    {
        // 初始化操作映射
        operationMap.put("setEmmAdminTrue", new OperationPair(
                () -> oppoSdkService.setEmmAdmin(true),
                () -> oppoSdkService.setEmmAdmin(false)
        ));
        operationMap.put("setDeviceOwner", new OperationPair(
                oppoSdkService::setDeviceOwner,
                oppoSdkService::clearDeviceOwner
        ));
        operationMap.put("setSuperWhiteList", new OperationPair(
                () -> oppoSdkService.setSuperWhiteList(List.of(packName)),
                () -> oppoSdkService.clearSuperWhiteList(List.of(packName))
        ));
        // 其他操作初始化...
        operationMap.put("addPersistentApp", new OperationPair(
                () -> oppoSdkService.addPersistentApp(packName),
                () -> oppoSdkService.removePersistentApp(packName)
        ));
        operationMap.put("addDisallowedUninstallPackages", new OperationPair(
                () -> oppoSdkService.addDisallowedUninstallPackages(packName),
                () -> oppoSdkService.removeDisallowedUninstallPackages(packName)
        ));
        operationMap.put("addAppAlarmWhiteList", new OperationPair(
                () -> oppoSdkService.addAppAlarmWhiteList(packName),
                () -> oppoSdkService.removeAppAlarmWhiteList(packName)
        ));
        operationMap.put("setSystemUpdatePolicies0", new OperationPair(
                () -> oppoSdkService.setSystemUpdatePolicies(0),
                () -> oppoSdkService.setSystemUpdatePolicies(1)
        ));
        operationMap.put("settingBatteryOptimizationsTrue", new OperationPair(
                () -> oppoSdkService.settingBatteryOptimizations(packName, true),
                () -> oppoSdkService.settingBatteryOptimizations(packName, false)
        ));
        operationMap.put("disableAppInLauncher", new OperationPair(
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, DISABLE_APP_IN_LAUNCHER_FLAG),
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, ENABLE_APP_IN_LAUNCHER_FLAG)
        ));
        operationMap.put("disableAppInRecentTask", new OperationPair(
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, DISABLE_APP_IN_RECENT_TASK_FLAG),
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, ENABLE_APP_IN_RECENT_TASK_FLAG)
        ));
    }

    // 反向操作列表，与正向操作相反
    public final List<String> reverseOperations = List.of(
            "setEmmAdminFalse", "clearDeviceOwner", "clearSuperWhiteList",
            "removePersistentApp", "removeDisallowedUninstallPackages",
            "removeAppAlarmWhiteList", "setSystemUpdatePolicies1",
            "settingBatteryOptimizationsFalse", "enableAppInLauncher",
            "enableAppInRecentTask"
    );

    // 补充反向操作到操作映射
    {
        operationMap.put("setEmmAdminFalse", new OperationPair(
                () -> oppoSdkService.setEmmAdmin(false),
                () -> oppoSdkService.setEmmAdmin(true)
        ));
        operationMap.put("clearDeviceOwner", new OperationPair(
                oppoSdkService::clearDeviceOwner,
                oppoSdkService::setDeviceOwner
        ));
        operationMap.put("clearSuperWhiteList", new OperationPair(
                () -> oppoSdkService.clearSuperWhiteList(List.of(packName)),
                () -> oppoSdkService.setSuperWhiteList(List.of(packName))
        ));
        // 其他反向操作初始化...
        operationMap.put("removePersistentApp", new OperationPair(
                () -> oppoSdkService.removePersistentApp(packName),
                () -> oppoSdkService.addPersistentApp(packName)
        ));
        operationMap.put("removeDisallowedUninstallPackages", new OperationPair(
                () -> oppoSdkService.removeDisallowedUninstallPackages(packName),
                () -> oppoSdkService.addDisallowedUninstallPackages(packName)
        ));
        operationMap.put("removeAppAlarmWhiteList", new OperationPair(
                () -> oppoSdkService.removeAppAlarmWhiteList(packName),
                () -> oppoSdkService.addAppAlarmWhiteList(packName)
        ));
        operationMap.put("setSystemUpdatePolicies1", new OperationPair(
                () -> oppoSdkService.setSystemUpdatePolicies(1),
                () -> oppoSdkService.setSystemUpdatePolicies(0)
        ));
        operationMap.put("settingBatteryOptimizationsFalse", new OperationPair(
                () -> oppoSdkService.settingBatteryOptimizations(packName, false),
                () -> oppoSdkService.settingBatteryOptimizations(packName, true)
        ));
        operationMap.put("enableAppInLauncher", new OperationPair(
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, ENABLE_APP_IN_LAUNCHER_FLAG),
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, DISABLE_APP_IN_LAUNCHER_FLAG)
        ));
        operationMap.put("enableAppInRecentTask", new OperationPair(
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, ENABLE_APP_IN_RECENT_TASK_FLAG),
                () -> oppoSdkService.setApplicationDisabledInLauncherOrRecentTask(packName, DISABLE_APP_IN_RECENT_TASK_FLAG)
        ));
    }

    public void rollback(List<OperationPair> executedOperations) {
        // 逆序执行补偿
        java.util.Collections.reverse(executedOperations);
        for (OperationPair pair : executedOperations) {
            try {
                pair.undo();
            } catch (Exception e) {
                // 补偿失败的处理（如记录日志）
                Log.e(TAG, "设置/取消监管补偿失败！", e);
            }
        }
    }
}
